package com.cgs.query.server.handler

import com.cgs.query.domain.*
import com.cgs.query.handler.PermissionObject
import com.cgs.query.handler.security.DefaultSecurityHandler
import com.cgs.query.server.service.publicSqlPoolName
import com.cgs.query.service.IQueryProjectService
import com.cgs.query.util.Utils
import org.springframework.util.CollectionUtils

/**
 * 处理lock权限问题
 */
class ServerSecurityHandler(
        private val projectService: IQueryProjectService
) : DefaultSecurityHandler() {

    override fun checkPermission(obj: PermissionObject) {
        val sameUser = fromOnePeople(obj.userId)
        //是否来自客户端,是否是同一用户的可允许操作
        if (fromClient(obj) || !(sameUser && obj.allowTheSameUserToOperate)) {
            //进行权限判断
            when (obj.type) {
                "queryDefine" -> {
                    //这里需要去判断,该定义被引用的项目中，是否被锁定
                    val queryDefine = (obj.obj as QueryDefine)
                    checkPermission(projectService.findByDefineId(queryDefine.id))
                }
                "queryProject", "project2Define" -> {
                    if (obj.projectName != publicSqlPoolName) {
                        val queryProject = Utils.notNull(projectService.findByName(obj.projectName!!), "找不到项目:${obj.projectName}")
                        if (queryProject.lockType != LockType.OPEN.name) {
                            throw SecurityException("该项目被锁定")
                        }
                    }else{



                    }
                }
                "querySource" -> {
                    val querySource = (obj.obj as QuerySource)
                    checkPermission(projectService.findBySourceId(querySource.id))
                }
                "executionObj" -> {
                    val executionObj = (obj.obj as ExecutionObj)
                    checkPermission(projectService.findByDefineIdAndVersion(executionObj.id, executionObj.version))
                }
                else -> {
                }
            }
        }
    }

    /**
     * 来自客户端,这里牵扯到用户信息是保存在哪里，如果是写死的，会出现来自同一个人
     */
    private fun fromClient(obj: PermissionObject): Boolean {
        return obj.type == "queryProject" && holder.getUserId().isEmpty()
    }

    /**
     * 来自同一个人
     */
    private fun fromOnePeople(userId: String?): Boolean = holder.getUserId() == userId


    private fun checkPermission(projects: Iterable<QueryProject>?) {
        val lockProjectList = projects?.filter { it.lockType != LockType.OPEN.name }?.toList()
        if (!CollectionUtils.isEmpty(lockProjectList)) {
            throw SecurityException("该操作被项目锁定: ${lockProjectList!!.joinToString { it.name }}")
        }
    }
}